﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Net;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json.Linq;

namespace _80X_CG_Frame.Utils
{
     public class WebApiUtil
    {
        private HttpClient client;

        public WebApiUtil(string uri, int timeout)
        {
            client = new HttpClient();
            client.BaseAddress = new Uri(uri);
            //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
            client.Timeout = TimeSpan.FromMilliseconds(timeout);

        }

        ~WebApiUtil()
        {
            client.Dispose();
        }
        public async Task<HttpResponseMessage> PostRequestAsync(JObject post_data, string uri = "")
        {
            string address = uri;
            if (uri == "")
                address = client.BaseAddress.AbsoluteUri;

            if (uri.StartsWith("https"))
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
            var str = "data=" + post_data.ToString();
            var content = new StringContent(str);
            //Console.WriteLine(str);
            //Console.WriteLine(Encoding.UTF8.GetString(await content.ReadAsByteArrayAsync()));
            content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
            content.Headers.ContentType.CharSet = "utf-8";
            var response = await client.PostAsync(address, content);
            return response;
        }
        public static async Task<string> GetResponseStringAsync(HttpResponseMessage response)
        {
            var result = await response.Content.ReadAsStringAsync();
            response.Dispose();
            return result;
        }

        /// <summary>
        /// 使用同步方法发送请求
        /// </summary>
        /// <param name="str"></param>
        /// <param name="uri"></param>
        /// <param name="timeout"></param>
        /// <returns>响应结果</returns>
        public static string PostRequest(string str, string uri, int timeout = 1000)
        {
            //string str = "";
            str = "data=" + str;
            byte[] data = Encoding.UTF8.GetBytes(str);
            var req = (HttpWebRequest)WebRequest.Create(uri);

            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = data.Length;
            req.Method = "POST";
            req.Timeout = timeout;

            //req.Headers.Set(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
            //req.Headers.Set(HttpRequestHeader.ContentLength, data.Length);

            using (var s = req.GetRequestStream())
            {
                s.Write(data, 0, data.Length);
            }
            var resp = req.GetResponse();
            var resp_str = "";
            using (var s = new StreamReader(resp.GetResponseStream()))
            {
                resp_str = s.ReadToEnd();
            }
            return "";
        }
        /// <summary>
        /// 使用同步方法发送请求
        /// </summary>
        /// <param name="str"></param>
        /// <param name="uri"></param>
        /// <param name="timeout"></param>
        /// <returns>响应结果</returns>
        public static string PostRequest(JObject post_data, string uri, int timeout = 1000)
        {
            //string str = "";
            var str = "data=" + post_data.ToString();
            byte[] data = Encoding.UTF8.GetBytes(str);
            var req = (HttpWebRequest)WebRequest.Create(uri);

            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = data.Length;
            req.Method = "POST";
            req.Timeout = timeout;

            //req.Headers.Set(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
            //req.Headers.Set(HttpRequestHeader.ContentLength, data.Length);

            using (var s = req.GetRequestStream())
            {
                s.Write(data, 0, data.Length);
            }
            var resp = req.GetResponse();
            var resp_str = "";
            using (var s = new StreamReader(resp.GetResponseStream()))
            {
                resp_str = s.ReadToEnd();
            }
            return resp_str;
        }
    }
}
